<?php

/**
 * API controller to check if user identified
 * by uid
 * IS FOLLOWING resource identified by 'type' ('q', 't', 'u')
 * and having value of "val"
 * For example /api/api.php?a=isfollowing&uid=3&t=u&val=23
 * Will return is_following = true IF user with id 3 IS FOLLOWING
 * user with id 23 (false if not following)
 *
 * /api/api.php?a=isfollowing&uid=3&t=q&val=125
 * Will return is_following = true if user with id 3
 * is following question with id 125
 *
 * /api/api.php?a=isfollowing&uid=3&t=t&val=eskimo
 * will return is_following = true if user with id 3
 * is following tag 'eskimo'
 *
 */

namespace StudyBuddy\Api\v1;

use StudyBuddy\Api\Api;

class Isfollowing extends Api {

    /**
     * Required params are uid and val
     *
     * @var array
     */
    protected $aRequired = array('uid', 'val');

    /**
     * Type of resource to check if
     * the user is following
     *
     * one of 3 possible types are
     * 'u'  - user (default)
     * 't' - tag
     * 'q' - question
     *
     * @var string
     */
    protected $type = 'u';
    protected $uid;
    protected $val;
    protected $isFollowing = false;

    protected function main() {
        $this->uid = $this->oRequest['uid'];
        $this->val = $this->oRequest['val'];
        $this->setType()
                ->getData()
                ->setOutput();
    }

    protected function setType() {
        $this->type = $this->oRequest->get('type', 's', 'u');

        return $this;
    }

    protected function getData() {
        switch ($this->type) {
            case 'u':
                $data = $this->oRegistry->Mongo->USERS->findOne(array('_id' => $this->uid, 'a_f_u' => array('$in' => array((int) $this->val))), array('_id' => 1));
                break;

            case 't':
                $data = $this->oRegistry->Mongo->USERS->findOne(array('_id' => $this->uid, 'a_f_t' => array('$in' => array($this->val))), array('_id' => 1));
                break;

            case 'q':
                $data = $this->oRegistry->Mongo->QUESTIONS->findOne(array('_id' => (int) $this->val, 'a_flwrs' => array('$in' => array($this->uid))), array('_id' => 1));
                break;
        }


        d('data: ' . print_r($data, 1));
        $this->isFollowing = !empty($data);

        return $this;
    }

    protected function setOutput() {

        $data = array('isfollowing' => $this->isFollowing);

        $this->oOutput->setData($data);

        return $this;
    }

}
